package com.yoga.app.interceptor;


import com.yoga.app.annotation.UserTokenManage;
import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.common.bo.YogaUserBO;
import com.yoga.common.util.Config;
import com.yoga.common.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenjin on 2019/6/26.
 */
public class SignInterceptor implements HandlerInterceptor {

    private Logger log = LoggerFactory.getLogger(SignInterceptor.class);


    private ValueOperations valueOperations;

    public  SignInterceptor(ValueOperations valueOperations){
        this.valueOperations=valueOperations;
    }


    /**
     * 项目签名私钥
     */
    private final static String secretKey = "yogaApp@1$";

    /**
     * 不需要登录的URL
     */
    private static Map<String, String> loginMap = new HashMap<>();

    static {
        loginMap.put("/app/upload-image","上传图片");
        loginMap.put("/app/send/code","发送验证码");
        loginMap.put("/app/register", "用户注册接口");
        loginMap.put("/app/login","登录");
        loginMap.put("/app/update/passwd","忘记修改密码");
        loginMap.put("/app/region/findAllProvince","查询省");
        loginMap.put("/app/region/findCityByCode","查询市");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //用于自测的时候放开接口签名验证
        if (StringUtils.isNotEmpty(request.getHeader("signStatus"))) {
            Integer signStatus = Integer.valueOf(request.getHeader("signStatus"));
            if (signStatus == 0) {
                return true;
            }
        }
        //接口签名验证
        String sign = request.getHeader("sign");
        String timestamp = request.getHeader("timestamp");

        if (StringUtils.isEmpty(sign) || StringUtils.isEmpty(timestamp)) {
            throw new AppException(AppErrorCodeEnum.SIGN_ISNULL);
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(secretKey).append(timestamp);
        String sysSign = MD5Util.encryption(buffer.toString());

        if (!sysSign.equals(sign)) {
            log.error("签名错误 ： sign:{},sysSign:{},timestamp:{}",sign,sysSign,timestamp);
            throw new AppException(AppErrorCodeEnum.SIGN_ERROR);
        }

        //不需要登录的接口过滤
        String url = request.getRequestURI();
        if (StringUtils.isNotBlank(loginMap.get(url))){
          return true;
        };

        String yogaUserId= (String) request.getHeader(Config.YOGA_USER_ID);
        if (StringUtils.isBlank(yogaUserId)){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }

        YogaUserBO yogaUserBO= UserTokenManage.getInstance(valueOperations).getLoginUser(Long.parseLong(yogaUserId));
        if (yogaUserBO==null){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }


}
